#include "common.h"

#define TAG "platform"

bool system_running = false;

tList driver_list;

elab_device_t* device_find(const char* const name)
{
    elab_device_t *ret = NULL;
    elab_assert(NULL != name);
    INTX_DISABLE();
    tNode *node = driver_list.headNode.nextNode;
    for(; node != (&driver_list.headNode); node = node->nextNode)
    {
        elab_device_t* device = container_of(node, elab_device_t, node);
        if(strlen(device->attr.name) != strlen(name))
        {

        }
        else if(0 == strncmp(device->attr.name, name, strlen(name)))
        {
            ret = device;   
        }
    }
    INTX_ENABLE();
    return ret;
}


void device_register(elab_device_t* device)
{
    elab_assert(NULL != device);
    INTX_DISABLE();
    if(device_find((const char* const)device->attr.name))
    {
        //do nothing!!
    }
    else
    {
        tListAddLast(&driver_list, &device->node);
    }
    INTX_ENABLE();
}


void device_unregister(elab_device_t* device)
{
    elab_assert(NULL != device);
    INTX_DISABLE();
    if(device_find((const char* const)device->attr.name))
    {
        tListRemove(&driver_list, &device->node);
    }
    else
    {
        //do nothing!!
    }
    INTX_ENABLE();
}


void platform_init(void)
{
    tListInit(&driver_list);
}
INIT_EXPORT(platform_init, EXPORT_PLATFORM);



int elab_device_read(elab_device_t *me,
                            char * buff, size_t lens)
{
    assert(me != NULL);
    assert(me->ops != NULL);
    assert(me->ops->read != NULL);
    int ret = me->ops->read(me, buff, lens);
    return ret;
}

int elab_device_write(elab_device_t *me,
                            const char *buff, size_t lens)
{
    assert(me != NULL);
    assert(me->ops != NULL);
    assert(me->ops->write != NULL);
    int ret = me->ops->write(me, buff, lens);
    return ret;
}

int elab_device_open(elab_device_t *me)
{
    assert(me != NULL);
    assert(me->ops != NULL);
    assert(me->ops->open != NULL);
    int ret = me->ops->open(me);
    return ret;
}

int elab_device_release(elab_device_t *me)
{
    assert(me != NULL);
    assert(me->ops != NULL);
    assert(me->ops->release != NULL);
    int ret = me->ops->release(me);
    return ret;
}

int elab_device_select(elab_device_t *me, unsigned int attr)
{
    assert(me != NULL);
    assert(me->ops != NULL);
    assert(me->ops->select != NULL);
    int ret = me->ops->select(me, attr);
    return ret;
}

void elab_system_running(void)
{
    system_running = true;
}
